import axios from 'axios'
// import { Promise } from 'core-js'
import { Message } from 'element-ui'
import store from '@/store'
import { getTokenTime } from '@/utils/auth.js'
import router from '@/router'

const timeout = 1 * 3600 * 1000
// 创建了一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
}
)

// 请求拦截器
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    if (isCheckTimeOut()) {
      store.commit('user/logout')
      router.push('/login')
      // 抛异常
      return Promise.reject(new Error('登录超时'))
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(({ data }) => {
  // 响应成功的回调
  const { data: res, success, message } = data
  if (success) return res
  Message.error(message)
  return Promise.reject(new Error(message))
}, error => {
  if (error.response && error.response.status === 401) {
    store.commit('user/logout')
    router.push('/login')
  } else { Message.error(error.message) }
  return Promise.reject(error)
})
// 检查时间戳过期
function isCheckTimeOut() {
  const currentDate = Date.now()
  const tokenTime = getTokenTime()
  return ((currentDate - tokenTime) >= timeout)
}

export default service

